import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import PageLoading from "@/components/PageLoading";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import { Card, Button, Icon, message, Row, Upload, Col } from 'antd';
import styles from './index.less';
import moment from 'moment';
import BackRouter from "@/pages/robotManagement/backRouter";
import MarkdownEditor from "@/utils/vditor";
import { postDebunkingRumorRecordSave, getDebunkingRumorRecordDetail } from '@/services/securityCenter';

class debunkingRumorsEdit extends Component {
    constructor(props) {
        super(props);
        this.state = {
            imageUrl: '',
            content: '',
            fileTitle: '',
            detailData: null,
        };
    }

    componentDidMount() {
        this.init()
    }

    init = async () => {
        const { location: { query } } = this.props;
        if (query && query.id) {
            let res = await getDebunkingRumorRecordDetail({ id: query.id });
            console.log(res);
            this.setState({ detailData: res, imageUrl: res.image, content: res.content, fileTitle: res.title })
        }
    }

    handleChangeImage = (file, type) => {
        if (file.file.status === "done") {
            this.setState({
                [type]: file.file.response.url,
            });
        }
    };

    /**
     * 上传图片前判断
     * @returns {*}
     */
    beforeUpload = (file) => {
        let b = /\.(png|jpg|gif)$/;
        let a = file.name.toLowerCase();

        const pig = b.test(a);
        const isJPG = file.type;
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!pig) {
            if (!isLt2M) {
                message.error("请上传小于2M的图片");
            } else {
                message.error("请上传图片格式");
            }
        } else {
            if (!isLt2M) {
                message.error("请上传小于2M的图片");
            }
        };
        return isJPG && isLt2M && pig;
    };

    doSubmit = (e, type) => {
		e.stopPropagation();
        e.preventDefault();
        switch (type) {
            case -1:
                this.nextRouter();
                break;

            case 0:
                this.onDraftSave()
                break;

            case 1:
                this.onPublicationSave()
                break;

            default:
                break;
        }
    }

    onDraftSave = async () => {
        const { location: { query: { id } } } = this.props;
        const { content, fileTitle, imageUrl } = this.state;
        let obj = {
            id,
            title: fileTitle,
            content,
            image: imageUrl,
            status: 0
        };
        let res = await postDebunkingRumorRecordSave(obj);
        console.log(res);
        if (res.code === 0) {
            message.success('操作成功');
            this.nextRouter();
        }
    }

    onPublicationSave = async () => {
        const { location: { query: { id } } } = this.props;
        const { content, fileTitle, imageUrl } = this.state;
        let obj = {
            id,
            title: fileTitle,
            content,
            image: imageUrl,
            status: 1
        };
        let res = await postDebunkingRumorRecordSave(obj);
        console.log(res);
        if (res.code === 0) {
            message.success('发布成功');
            this.nextRouter();
        }
    }

    nextRouter = () => {
        const { dispatch } = this.props;
        let pathname = "/debunkingRumors";
        dispatch(routerRedux.push({ pathname }));
    }

    render() {
        const { imageUrl, content, fileTitle } = this.state;

        return (
            <Suspense fallback={<PageLoading />}>
                <PageHeaderWrapper>
                    <Row className={styles.colorBackground}>
                        <Col style={{ padding: 10, color: "#4B5475", fontWeight: 600 }} xs={24}>
                            <div className={styles.title}>
                                <span>编辑文章</span>
                            </div>
                        </Col>
                        <div style={{ position: "absolute", right: 20, top: 16, zIndex: 2 }}>
                            <BackRouter pathname='/debunkingRumors'></BackRouter>
                        </div>
                    </Row>
                    <Card bordered={false}>
                        <MarkdownEditor
                            value={this.state.content}
                            title={this.state.fileTitle}
                            name='markdown-editor'
                            id='markdown-editor'
                            height='400px'
                            width='700'
                            onChange={(value, type) => {
                                switch (type) {
                                    case 'content':
                                        this.setState({ content: value });
                                        break;
                                    case 'title':
                                        this.setState({ fileTitle: value });
                                        break;
                                }
                            }}
                            ref={(r) => (this.vEditor = r)}
                        />
                        <div style={{ marginTop: 16, display: 'flex', gap: 20 }} className={styles.imagesURLcalss}>
                            <span style={{ fontSize: '18px', fontWeight: 'bold' }}>添加封面</span>
                            <span>
                                <Upload
                                    name='file'
                                    listType='picture'
                                    showUploadList={false}
                                    action='/cloud/file/upload'
                                    beforeUpload={this.beforeUpload}
                                    onChange={(info) => this.handleChangeImage(info, "imageUrl")}
                                    accept='.png,.jpg'
                                >
                                    {imageUrl ? (
                                        <img src={fileUrl+imageUrl} alt="avatar" style={{ width: '238px', height: '118px' }} />
                                    ) : (
                                        <div className={styles.uploadClass}>
                                            <span style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
                                                <Icon type='plus' style={{ fontSize: '20px' }} />
                                                <span>添加文章封面</span>
                                            </span>
                                        </div>
                                    )}
                                </Upload>
                                <span style={{ marginTop: 6, display: 'block' }}>图片上传格式支持 JPEG、JPG、PNG</span>
                            </span>
                        </div>

                        <div style={{ display: 'flex', justifyContent: 'center', gap: 24, margin: '20px 0' }}>
                            <Button onClick={e => this.doSubmit(e, -1)}>取消编辑</Button>
                            <Button onClick={e => this.doSubmit(e, 0)}>保存草稿</Button>
                            <Button type="primary" onClick={e => this.doSubmit(e, 1)}>确认发布</Button>
                        </div>
                    </Card>
                </PageHeaderWrapper>
            </Suspense>
        );
    }
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(debunkingRumorsEdit);
